<template>
  <div>
    <!-- <el-button
      class="diy-grid-setting"
      round
      plain
      size="medium"
      icon="el-icon-download"
      :loading="downloadLoading"
      @click.stop="download"
    ></el-button> -->
    <div class="diy-grid-setting" @click.stop="drawer = true">
      <i class="sc-icon-file-excel-2-fill"></i>
    </div>
    <el-drawer title="数据操作" v-model="drawer" destroy-on-close>
      <div class="button">
        <el-button type="primary" :loading="downloadLoading" @click="upbarcode" plain>更新条码</el-button>

        <el-button type="primary" :loading="downloadLoading" @click="stockStatus" plain>库存同步状态</el-button>
        <el-button type="primary" :loading="downloadLoading" @click="stocks" plain>生成库存表</el-button>
        <el-button @click="download" type="success" icon="el-icon-download" plain>导出</el-button>
        <el-upload class="upload-demo" action="" :on-change="handleChange" :on-remove="handleRemove"
          :on-exceed="handleExceed" accept=".xls,.xlsx" :limit="1" :auto-upload="false">
          <el-button type="success" icon="el-icon-upload2" plain>编码导入</el-button>
        </el-upload>
        <el-upload class="upload-demo" action="" :on-change="luxuryData" :on-remove="handleRemove"
          :on-exceed="handleExceed" accept=".xls,.xlsx" :limit="1" :auto-upload="false">
          <el-button type="success" icon="el-icon-upload2" plain>奢品导入</el-button>
        </el-upload>

        <el-button type="success" :loading="downloadLoading" @click="backs" plain>备份</el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { reactive, toRefs } from "@vue/reactivity";
import {
  backups,
  updatebarcode,
  upstocks,
  selstock_status,
  uploadXlsx,
  uploadLuxury,
} from "@/api/pandian";
import { ElMessage } from "element-plus";
export default {
  props: {
    multipleTable: {
      type: Object,
    },
  },
  setup(props) {
    const data = reactive({
      downloadLoading: false,
      drawer: false,
      fileTemp: "",
    });
    const exportExcel = (tableRef, filename, selection) => {
      data.downloadLoading = true;
      // 采用动态导入
      import("@/utils/Export2Excel").then((excel) => {
        excel.export_table_to_excel({ tableRef, filename, selection });
        data.downloadLoading = false;
      });
    };
    const download = () => {
      console.log(props.multipleTable);
      exportExcel(props.multipleTable, "盘点结果");
    };
    //备份
    const backs = async () => {
      const result = await backups.get();
      if (result.code == 200) {
        ElMessage.success({
          message: "备份成功！",
          type: "success",
        });
      } else {
        ElMessage.success({
          message: "失败！",
          type: "error",
        });
      }
    };

    //生成库存表
    const stocks = async () => {
      const result = await upstocks.get();
      if (result.code != 200) {
        ElMessage.error({
          showClose: true,
          message: "我失败了。。。",
          type: "error",
        });
        return;
      }
      ElMessage.success({
        message: "正在同步，请等待十分钟",
        type: "success",
      });
    };
    //更新条码
    const upbarcode = async () => {
      const result = await updatebarcode.get();
      if (result.code != 200) {
        ElMessage.error({
          showClose: true,
          message: "我失败了。。。",
          type: "error",
        });
        return;
      }
      ElMessage.success({
        message: "条码已更新！",
        type: "success",
      });
    };
    //查询库存同步状态
    const stockStatus = async () => {
      const result = await selstock_status.get();
      const flag = {};
      switch (result.data[0].flag) {
        case 0:
          flag.message = "库存已同步完成！";
          flag.type = "success";
          break;
        case 1:
          flag.message = "库存正在同步中！";
          flag.type = "success";
          break;
        case 2:
          flag.message = "erp超时，此次数据不准确，待同步结束后重新同步！";
          flag.type = "error";
          break;
      }
      ElMessage(flag);
    };
    //上传文件时处理方法
    const handleChange = async (file) => {
      data.fileTemp = file.raw;
      if (data.fileTemp) {
        if (
          data.fileTemp.type ==
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          data.fileTemp.type == "application/vnd.ms-excel"
        ) {
          // 采用动态导入
          import("@/utils/importfile").then((excel) => {
            excel.importfile(data.fileTemp, async (outdata) => {
              console.log(outdata);
              if (Object.keys(outdata[0])[0] != "商品编码") {
                ElMessage({
                  type: "warning",
                  message: "附件格式错误，请删除后重新上传！",
                });
                return;
              }
              let str = "";
              let list = [];
              let key = 1;
              outdata.forEach((ele, index) => {
                if (index == 500 * key) {
                  str = str.replace(/,$/gi, "");
                  list[key - 1] = str;
                  str = "";
                  key++;
                }
                str += `('${ele["商品编码"]}'),`;
              });

              str = str.replace(/,$/gi, "");
              list[key - 1] = str;
              console.log(list);
              console.log(uploadXlsx);
              //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
              //此处可对数据进行处理
              const result = await uploadXlsx.post({
                outdata: JSON.stringify(list),
              });
              if (result.code != 200) {
                ElMessage({
                  type: "warning",
                  message: result.data,
                });
              }
              ElMessage.success({
                message: "上传成功！",
                type: "success",
              });
            });
          });
        } else {
          ElMessage({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        ElMessage({
          type: "warning",
          message: "请上传附件！",
        });
      }
    };
    //上传奢品仓数据
    const luxuryData = async (file) => {
      data.fileTemp = file.raw;
      if (data.fileTemp) {
        if (
          data.fileTemp.type ==
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          data.fileTemp.type == "application/vnd.ms-excel"
        ) {
          //配置上传excel请求头
          const config = {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          };
          const formData = new FormData();
          formData.append("file", data.fileTemp);
          console.log(data.fileTemp);
          const result = await uploadLuxury.from(formData, config);
          if (result.code != 200) {
            ElMessage({
              type: "warning",
              message: result.data,
            });
          }
          ElMessage.success({
            message: "上传成功！",
            type: "success",
          });
        }
      } else {
        ElMessage({
          type: "warning",
          message: "请上传附件！",
        });
      }
    };
    //超出最大上传文件数量时的处理方法
    const handleExceed = () => {
      ElMessage({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    };
    //移除文件的操作方法
    const handleRemove = () => {
      data.fileTemp = null;
    };

    return {
      ...toRefs(data),
      download,
      backs,
      stocks,
      upbarcode,
      stockStatus,
      handleChange,
      handleExceed,
      handleRemove,
      luxuryData,
    };
  },
};
</script>
<style scoped>
.diy-grid-setting {
  position: fixed;
  width: 40px;
  height: 40px;
  border-radius: 3px 0 0 3px;
  bottom: 180px;
  right: 0px;
  z-index: 100;
  background: #409eff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.diy-grid-setting i {
  font-size: 18px;
  color: #fff;
}

.button {
  /* display: flex;
    flex-direction: column;
    width: 100px; */
  margin: 20px;
  display: flex;
  flex-wrap: wrap;
}

.button .el-button {
  margin: 5px;
}
</style>